package com.hsnn.medstgmini.base.dict.dao.impl;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.hsnn.medstgmini.base.dict.dao.DicAreaLogDao;
import com.hsnn.medstgmini.base.dict.model.DicAreaLog;
import com.hsnn.medstgmini.dao.HibernateSqlUtil;
import com.hsnn.medstgmini.util.Pagination;
import com.hsnn.medstgmini.util.ParseDate;

@Repository("dicAreaLogDao")
public class DicAreaLogDaoImpl extends BaseHibernateDAO implements DicAreaLogDao {
	
	@Resource(name = "sessionFactory")
	private SessionFactory factory;
	
	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;

	@Autowired
	private HibernateSqlUtil dao;
	
	/**
	 * 基础库 数据字典 地区字典维护记录
	 * @param page
	 * @return
	 */
	public Pagination getLogData(Pagination page) {
		String areaId = page.getConditions().get("areaid");
		String startDate = page.getConditions().get("startDate");
		String endDate = page.getConditions().get("endDate");
		
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT a.log_id, a.detail, a.upd_datetime as literUpdDttm,  b.name as updUser");
		
		StringBuffer sqlSubfix = new StringBuffer().append(" from dic_area_log a, sys_user b where a.upd_user = b.id ");
		StringBuffer sqlCount = new StringBuffer().append("select count(*) ");
		StringBuffer sqlOrder = new StringBuffer(" order by a.upd_datetime desc ");

		sql.append(sqlSubfix);
		sqlCount.append(sqlSubfix);
        if (StringUtils.isNotBlank(areaId)) {
        	sql.append(" and a.area_id = :areaId");
        	sqlCount.append(" and a.area_id = :areaId");
        }		
		
        if (StringUtils.isNotBlank(startDate)) {
        	sql.append(" and a.upd_datetime >= :startDate");
        	sqlCount.append(" and a.upd_datetime >= :startDate");
        }

        if (StringUtils.isNotBlank(endDate)) {
        	sql.append(" and a.upd_datetime <= :endDate");
        	sqlCount.append(" and a.upd_datetime <= :endDate");
        }
        sql.append(sqlOrder);

		Query query = getSession().createSQLQuery(sql.toString());
		Query queryCount = getSession().createSQLQuery(sqlCount.toString());
        if (StringUtils.isNotBlank(areaId)) {
        	query.setString("areaId", areaId);
        	queryCount.setString("areaId", areaId);
        }		
		
        if (StringUtils.isNotBlank(startDate)) {
        	query.setString("startDate", startDate);
        	queryCount.setString("startDate", areaId);
        }

        if (StringUtils.isNotBlank(endDate)) {
        	query.setString("endDate", endDate);
        	queryCount.setString("endDate", areaId);
        }
        
		BigInteger bi = (BigInteger)queryCount.uniqueResult();
		page.setRecords(bi.longValue());
		query.setFirstResult(page.getFirstResult());
		query.setMaxResults(page.getMaxResults());
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		page.setRows(query.list());
		return page;
	}
	
    public Pagination getAllHis(Pagination page) {
		Criteria criteria = getSession().createCriteria(DicAreaLog.class);
		Map<String, String> map = page.getConditions();
		if (null != map && map.size() > 0) {
			if (StringUtils.isNotBlank(map.get("areaid"))){
				criteria.add(Restrictions.eq("areaId", map.get("areaid").trim()));
			}
			if (StringUtils.isNotBlank(map.get("startDate"))){
				criteria.add(Restrictions.ge("updDatetime", ParseDate.fromFullFormat(map.get("startDate").trim())));
			}
			if (StringUtils.isNotBlank(map.get("endDate"))){
				criteria.add(Restrictions.le("updDatetime", ParseDate.fromFullFormat(map.get("endDate").trim())));
			}
		}
		criteria.addOrder(Order.desc("updDatetime"));  
		Long totalCount = (Long) criteria.setProjection(Projections.rowCount()).uniqueResult();  
		criteria.setProjection(null);  
		criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);  
		criteria.setFirstResult((page.getPage()-1)*page.getMaxResults());  
		criteria.setMaxResults(page.getMaxResults());  
		List<DicAreaLog> records = criteria.list();  
		page.setRecords(totalCount);  
		page.setTotal(new Long(totalCount%page.getMaxResults()==0?totalCount/page.getMaxResults():totalCount/page.getMaxResults()+1).intValue());
		page.setRows(records);  
		return page;
    }

    /**
	 * 基础库 数据字典 地区字典 根据id查询地区 日志详情
	 * @param page
	 * @return
	 */
    @SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> getAreaLogDetail(Pagination page) {
    	String sql = "select t.area_id,t.area_name,t.father_id,t.ar_shortname,t.ar_fullname,t.status,t.detail,"
    			+ "DATE_FORMAT(t.upd_datetime,'%Y-%m-%d %T') as upd_datetime,u.name as upd_user "
    			+ "from dic_area_log t left join sys_user u on t.upd_user=u.id where t.log_id=:logId";
    	Map<String, Object> params = new HashMap<String, Object>();
    	params.put("logId", page.getConditions().get("logId"));
    	List<Map<String, Object>> list = (List<Map<String, Object>>) dao.getSqlMapList(sql.toString(), params);
    	Map<String, Object> data = list.get(0);
    	return data;
	}
    
    public Pagination getLasLogInfo(Pagination page){
    	
    	String logId = page.getConditions().get("logId");
    	
    	StringBuffer sql = new StringBuffer();
    	sql.append("select * from dic_area_log b, ")
    	   .append("(select log_id, area_id, upd_datetime from dic_area_log where log_id= :logId) a")
    	   .append(" where b.area_id = a.area_id and b.upd_datetime <= a.upd_datetime order by b.upd_datetime desc limit 0, 2 ");
    	
		Query query = getSession().createSQLQuery(sql.toString());
		query.setString("logId", logId);
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		page.setRows(query.list());
    	return page;  
    	
    	/*
    	StringBuffer sql = new StringBuffer()
    	.append("select t.area_id,t.area_name,t.father_id,t.ar_shortname,t.ar_fullname,t.status,t.detail,")
    	.append("DATE_FORMAT(t.upd_datetime,'%Y-%m-%d %T') as upd_datetime,u.name as upd_user")
    	.append(" from dic_area_log t")
    	.append(" left join sys_user u on t.upd_user=u.id")
    	.append(" where t.area_id=:areaId")
    	.append("  and DATE_FORMAT(t.upd_datetime,'%Y-%m-%d %T')<:updTime");
    	Map<String, Object> params = new HashMap<String, Object>();
    	params.put("areaId", areaId);
    	params.put("updTime", updtime);
    	List<Map<String, Object>> list = (List<Map<String, Object>>) dao.getSqlMapList(sql.toString(), params);
    	if (null != list && list.size() > 0){
    		return list.get(0);
    	}
    	return null;
    	*/
    }
    
    public String addDicAreaLog(DicAreaLog data){
    	getSession().save(data);
    	return "success";
    }   
}